<!-- 平板端-app管理 -->
<script>
import { enc, SHA1 } from 'crypto-js'

import {
  addOrUpdateApk,
  deleteApk,
  queryApkList,
  uploadApkFile
} from '@/api/pad'

export default {
  name: 'AppManagement',
  computed: {
    dialogTitle() {
      return (this.isEdit ? '编辑' : '新增') + '安装包'
    }
  },
  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      formModel: {
        fileId: '',
        version: '',
        versionNumber: '',
        sha1: '',
        remark: ''
      },
      formRules: {
        fileId: [
          {
            message: '请上传安装包',
            required: true
          }
        ],
        version: [
          {
            message: '请输入版本号',
            required: true
          }
        ],
        versionNumber: [
          {
            message: '请输入版本值',
            required: true
          }
        ],
        sha1: [
          {
            message: '请获取SHA1值',
            required: true
          }
        ]
      },
      apkList: [],
      fileList: []
    }
  },
  methods: {
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    queryApkFiles() {
      queryApkList()
        .then((res) => {
          if (res.success) {
            this.apkList = res.data || []
          } else {
            this.apkList = []
            this.$message.error(
              res.message || '查询安装包失败'
            )
          }
        })
        .catch((err) => {
          this.apkList = []
          this.$message.error(err)
        })
    },
    handleAddClick() {
      this.isEdit = false
      this.dialogVisible = true
    },
    handleUpdateClick(data) {
      console.log('data', data)
      this.formModel = {
        ...data
      }
      this.isEdit = true
      this.dialogVisible = true
    },
    handleDeleteClick(data) {
      this.$confirm(
        '此操作将永久删除该安装包，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteApk(data.sha1).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.queryApkFiles()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
        })
        .catch(() => {
          console.warn('取消删除操作')
        })
    },
    handleFilesChange(file) {
      this.fileList = [file]
      this.calculateFileSHA1(file.raw)
    },
    handleFilesExceed(files) {
      this.fileList = [files[0]]
      this.calculateFileSHA1(files[0].raw)
    },
    handleFilesRemove() {
      this.formModel.fileId = ''
      this.formModel.sha1 = ''
    },
    handleSubmitClick() {
      console.log('form', this.formModel)
      console.log('fileList', this.fileList)
      if (!this.fileList.length) {
        this.$refs.formRef.validateField('fileId')
      } else {
        if (this.formModel.fileId) {
          this.$refs.formRef.validate((valid) => {
            if (valid) {
              this.submitData()
            }
          })
        } else {
          this.uploadApk(this.fileList[0].raw)
            .then((fileId) => {
              console.log('上传成功', fileId)
              this.formModel.fileId = fileId
              this.$refs.formRef.validate((valid) => {
                if (valid) {
                  this.submitData()
                }
              })
            })
            .catch((err) => {
              this.$message.error(err)
            })
        }
      }
    },
    submitData() {
      addOrUpdateApk(this.formModel).then((res) => {
        if (res.success) {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.queryApkFiles()
        } else {
          this.$message.error(res.message || '操作失败')
        }
      })
    },
    async uploadApk(file) {
      const formData = new FormData()
      formData.append('file', file)
      return new Promise((resolve, reject) => {
        uploadApkFile(formData)
          .then((res) => {
            if (res.success) {
              resolve(res.data)
            } else {
              reject(res.message || '上传安装包失败')
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async calculateFileSHA1(file) {
      const text = await this.readFileAsync(file)
      const hash = SHA1(enc.Utf8.parse(text)) // 或 enc.Utf8.parse
      this.formModel.sha1 = hash.toString()
    },
    readFileAsync(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsText(file)
      })
    },
    afterDialogClosed() {
      this.fileList = []
      this.$refs.formRef.resetFields()
    }
  },
  mounted() {
    this.queryApkFiles()
  }
}
</script>

<template>
  <div class="body">
    <div class="table-wrap">
      <div class="search_header">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleAddClick"
        >
          新增安装包
        </el-button>
      </div>

      <el-table
        :data="apkList"
        :header-cell-style="{
          background: '#F2F6FB ',
          color: ' #6B767D'
        }"
        :row-class-name="tableRowClassName"
        row-key="sha1"
      >
        <el-table-column
          label="版本号"
          prop="version"
          show-overflow-tooltip
        />
        <el-table-column
          label="版本值"
          prop="versionNumber"
          show-overflow-tooltip
        />
        <el-table-column
          label="说明"
          prop="remark"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div
              v-if="scope.row.remark"
              style="
                display: inline-flex;
                flex-direction: column;
              "
            >
              <span
                v-for="(
                  item, index
                ) in scope.row.remark.split('\n')"
                :key="index"
              >
                {{ item }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleUpdateClick(scope.row)"
              style="color: #00baff; font-weight: 400"
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="handleDeleteClick(scope.row)"
              style="color: #ff5b5b; font-weight: 400"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @closed="afterDialogClosed"
    >
      <el-form
        ref="formRef"
        label-position="left"
        label-width="80px"
        :model="formModel"
        :rules="formRules"
      >
        <el-form-item label="安装包" prop="fileId">
          <el-upload
            accept=".apk"
            action="#"
            :auto-upload="false"
            :drag="false"
            :file-list="fileList"
            :limit="1"
            :on-change="handleFilesChange"
            :on-exceed="handleFilesExceed"
            :on-remove="handleFilesRemove"
          >
            <el-button type="primary"> 点击上传 </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="版本号" prop="version">
          <el-input v-model="formModel.version" />
        </el-form-item>

        <el-form-item label="版本值" prop="versionNumber">
          <el-input-number
            v-model="formModel.versionNumber"
            :min="1"
            :step="1"
          />
        </el-form-item>

        <el-form-item label="SHA1值" prop="sha1">
          <el-input
            v-model="formModel.sha1"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item label="更新说明" prop="remark">
          <el-input
            v-model="formModel.remark"
            type="textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmitClick"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';

.el-table {
  margin-top: 13px;
}

:deep(.el-dialog) {
  .el-dialog__header {
    background: #597182 !important;
    padding: 8px 0 14px 24px !important;
    height: 39px !important;

    .el-dialog__title {
      font-size: 16px !important;
      line-height: 22px;
      font-weight: 400 !important;
      color: white !important;
      //margin:19px 0 14px 24px !important;
    }

    .el-dialog__headerbtn {
      font-size: 16px;
      top: 10px !important;
      right: 17px !important;
      color: white !important;

      .el-dialog__close {
        color: white !important;
      }
    }
  }

  .el-dialog__body {
    padding: 17px 32px 18px 26px !important;

    .el-form-item {
      margin-bottom: 19px !important;
    }
  }

  .el-input__inner {
    background-color: #f6f9fc !important;
  }

  .el-button--default {
    border-color: #497fa3 !important;

    span {
      color: #497fa3 !important;
    }
  }

  .el-button--primary {
    background: #497fa3 !important;
    border-color: white !important;
  }
}
</style>
